
#include "Acceptor.h"

#include <fcntl.h>
#include <utility>
#include "Channel.h"
#include "Socket.h"
#include "macro.h"

Acceptor::Acceptor(EventLoop *loop) {
  m_socket = std::make_unique<Socket>();
  MYWEB_ASSERT(m_socket->Create() == RC_SUCCESS);
  MYWEB_ASSERT(m_socket->Bind("127.0.0.1", 1234) == RC_SUCCESS);
  MYWEB_ASSERT(m_socket->Listen() == RC_SUCCESS);

  m_channel = std::make_unique<Channel>(m_socket->fd(), loop);

  m_channel->set_read_callback([this](){
      this->AcceptConnection();
  });
  m_channel->EnableRead();
}

Acceptor::~Acceptor() {}

RC Acceptor::AcceptConnection() const{
  int clnt_fd = -1;
  if( m_socket->Accept(clnt_fd) != RC_SUCCESS ) {
    return RC_ACCEPTOR_ERROR;
  }
  // TODO: remove
  fcntl(clnt_fd, F_SETFL, fcntl(clnt_fd, F_GETFL) | O_NONBLOCK);  // 新接受到的连接设置为非阻塞式
  if (m_new_connection_callback) {
    m_new_connection_callback(clnt_fd);
  }
  return RC_SUCCESS;
}

void Acceptor::set_new_connection_callback(std::function<void(int)> const &callback) {
  m_new_connection_callback = callback;
}
